package cn.com.taiji.oospub.wechat.controller.login;


import cn.com.taiji.manager.ManagerException;
import cn.com.taiji.oospub.wechat.common.helper.ForegroundLoginHelper;
import cn.com.taiji.oospub.wechat.common.helper.WXLoginHelper;
import cn.com.taiji.oospub.wechat.controller.WXBaseLogController;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.service.IMemberBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信登录
 *
 * @author fancw
 */
//@Controller
public class LoginController extends WXBaseLogController {


    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;

    /**
     * 登录
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/wx/login/manage", method = RequestMethod.POST)
    public void loginPost(@RequestBody MemberBaseInfo entity,
                          HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            MemberBaseInfo memInfo = memberBaseInfoService.getByLoginName(entity.getLoginName());
            if (memInfo == null) {
                throw new ManagerException("该账号不存在");
            } else {
                if (!ForegroundLoginHelper.isPassValid(entity.getPasswd(), memInfo)) {
                    throw new ManagerException("密码不正确");
                } else {
                    if (!"正常".equals(memInfo.getStatus().getValue())) {
                        throw new ManagerException("账号不可用");
                    }
                }
            }
            memInfo.setActiveStr(memInfo.getActive().getValue());
            WXLoginHelper.setSession(request, memInfo);
            super.addLoginLog(request, "登录({})成功", entity.getLoginName());
            writeSuccessToBrowers("登录成功", response);
        } catch (Exception e) {
            writeFailToBrowers(e.getMessage(), response);
        }
    }
}
